package com.tt.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tt.reggie.common.BaseContext;
import com.tt.reggie.common.R;
import com.tt.reggie.dto.DishDto;
import com.tt.reggie.entity.Category;
import com.tt.reggie.entity.Dish;
import com.tt.reggie.entity.DishFlavor;
import com.tt.reggie.service.CategoryService;
import com.tt.reggie.service.DishFlavorService;
import com.tt.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto, HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        dishService.savaWithFlavor(dishDto);
        //删除redis中的数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("新增菜品成功！");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //查询条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name!=null,Dish::getName,name);
        //分页查询
        dishService.page(dishPage,dishLambdaQueryWrapper);

        //构造dto分页构造器
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();
        List<DishDto> collect = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            Category byId = categoryService.getById(item.getCategoryId());

            BeanUtils.copyProperties(item, dishDto);
            dishDto.setCategoryName(byId.getName());
            return dishDto;

        }).collect(Collectors.toList());

        dishDtoPage.setRecords(collect);
        return R.success(dishDtoPage)   ;
    }


    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable long id){
        DishDto dishById = dishService.getDishById(id);

        return R.success(dishById);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto,HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        dishService.updateWithFlavor(dishDto);
        //删除redis中的数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("更改成功！");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //判断是否为启售，若为启售则无法删除
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId,ids);
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        int count = dishService.count(dishLambdaQueryWrapper);
        if(count>0){
            return R.error("启售的菜品不能删除，先将要删除的菜品停售");
        }
        //若不存在启售的菜品，则删除
        dishService.removeByIds(ids);

        //删除与菜品关联的口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        for(Long id : ids){
//            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id).or();
//        }
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //删除redis中的数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("删除成功！");
    }


    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids,HttpServletRequest request){
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);

        List<Dish> dishes = new ArrayList<>();
        for (Long id:ids){
            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(id);
            dishes.add(dish);
        }
        dishService.updateBatchById(dishes);
        //删除redis中的数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("更改成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> getByCategoryId(Long categoryId){
        String key = "dish_"+categoryId;
        List<DishDto> dtoList = null;
        //获取redis中的菜品数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在则直接返回redis中的数据
        if(dtoList!=null){
            return R.success(dtoList);
        }
        //如果不存在则执行数据库查询
        //查询条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,categoryId).eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        dtoList = new ArrayList<>();
        for(Dish dish : list){
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish,dishDto);
            Long dishId = dish.getId();
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavors);
            dtoList.add(dishDto);
        }
        //查询完将数据添加进redis
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }






}
